package com.rbac.application.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.application.service.MenuService;
import com.rbac.common.utils.TreeUtils;
import com.rbac.domain.dto.response.MenuResponse;
import com.rbac.domain.entity.Menu;
import com.rbac.infrastructure.mapper.MenuMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    public List<MenuResponse> getUserMenus(Long userId) {
        List<Menu> userMenus = baseMapper.getMenusByUserId(userId);
        List<MenuResponse> menuResponses = userMenus.stream()
                .map(this::convertToMenuResponse)
                .collect(Collectors.toList());
        
        return TreeUtils.buildMenuTree(menuResponses);
    }

    @Override
    public List<Menu> getMenuTree() {
        List<Menu> allMenus = baseMapper.getMenuTree();
        return TreeUtils.buildTree(allMenus, 0L);
    }

    @Override
    public Menu createMenu(Menu menu) {
        menu.setCreatedTime(LocalDateTime.now());
        this.save(menu);
        return menu;
    }

    @Override
    public Menu updateMenu(Menu menu) {
        menu.setUpdatedTime(LocalDateTime.now());
        this.updateById(menu);
        return menu;
    }

    @Override
    public void deleteMenu(Long id) {
        this.removeById(id);
    }

    private MenuResponse convertToMenuResponse(Menu menu) {
        MenuResponse response = new MenuResponse();
        response.setId(menu.getId());
        response.setMenuName(menu.getMenuName());
        response.setMenuCode(menu.getMenuCode());
        response.setParentId(menu.getParentId());
        response.setMenuType(menu.getMenuType());
        response.setPath(menu.getPath());
        response.setComponent(menu.getComponent());
        response.setIcon(menu.getIcon());
        response.setSortOrder(menu.getSortOrder());
        response.setVisible(menu.getVisible());
        return response;
    }
}